<template>
  <div class="card">
    <div class="card-header">
      <div class="card-header-title">
        <span>收藏网站</span>
      </div>
      <div class="card-header-toolbar">
        <a-space :size="16" class="toolbar-space">
          <a-input
            v-model:value="where.searchText"
            placeholder="网站名称、地址（回车搜索）"
            @pressEnter="reload"
            @input="onSearchInput"
            class="search-input"
          >
            <template #prefix>
              <icon-font iconClass="icon-opt-search"></icon-font>
            </template>
          </a-input>
          <a-button class="border-radius reset-btn" @click="clear">
            <span class="btn-text">重置</span>
          </a-button>
          <a-select
            v-model:value="where.sortField"
            class="sort-field-select"
            @change="reload"
            placeholder="排序字段"
          >
            <a-select-option value="clickCount">点击次数</a-select-option>
            <a-select-option value="updateTime">更新时间</a-select-option>
          </a-select>
          <a-select
            v-model:value="where.sortOrder"
            class="sort-order-select"
            @change="reload"
            placeholder="排序方式"
          >
            <a-select-option value="desc">降序</a-select-option>
            <a-select-option value="asc">升序</a-select-option>
          </a-select>
          <a-button type="primary" class="border-radius add-btn" @click="openAddEdit()">
            <plus-outlined />
            <span class="btn-text">新建</span>
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="card-body">
      <div class="site-list">
        <a-spin :spinning="loading">
          <template v-if="dataSource && dataSource.length > 0">
            <div class="site-grid">
              <a-card
                v-for="site in dataSource"
                :key="site.bookmarkId"
                hoverable
                :class="['site-card', { 'site-card-pinned': site.pinned === 'Y' }]"
                @click="openSite(site)"
              >
                <a-card-meta>
                  <template #title>
                    <div class="site-header">
                      <img :src="site.icon" :alt="site.name" class="site-icon" />
                      <span class="site-name">{{ site.name }}</span>
                    </div>
                  </template>
                  <template #description>
                    <div class="site-info">
                      <div class="site-url">{{ site.url }}</div>
                      <div class="site-footer">
                        <div class="site-stats">
                          <span>点击次数：{{ site.clickCount || 0 }}</span>
                        </div>
                        <div class="site-actions" @click.stop>
                          <a-button type="link" size="small" @click="openAddEdit(site)">
                           <template #icon><edit-outlined /></template>
                        </a-button>
                        <a-button type="link" size="small" @click="remove(site)">
                          <template #icon><delete-outlined /></template>
                        </a-button>
                        <a-button type="link" size="small" @click="togglePin(site)">
                          <template #icon><pushpin-outlined /></template>
                        </a-button>
                         
                        </div>
                      </div>
                    </div>
                  </template>
                </a-card-meta>
              </a-card>
            </div>
            <div class="pagination-container">
              <a-pagination
                :current="pageNo"
                :pageSize="pageSize"
                :total="total"
                :show-size-changer="true"
                :show-quick-jumper="true"
                @change="handlePageChange"
                @showSizeChange="handleSizeChange"
              />
            </div>
          </template>
          <template v-else>
            <div class="empty-tip">
              <a-empty description="暂无数据" />
            </div>
          </template>
        </a-spin>
      </div>
    </div>

    <!-- 新增编辑弹框 -->
    <a-modal
      :visible="showEdit"
      @update:visible="(val) => showEdit = val"
      :title="isEdit ? '编辑收藏' : '添加收藏'"
      @ok="handleSubmit"
      @cancel="() => showEdit = false"
      :confirm-loading="addLoading"
      :maskClosable="false"
      :destroyOnClose="true"
      class="bookmark-modal"
    >
      <a-form :form="formRef">
        <a-form-item label="网站名称" name="name" :rules="[{ required: true, message: '请输入网站名称' }]">
          <a-input v-model:value="formState.name" placeholder="请输入网站名称" />
        </a-form-item>
        <a-form-item label="网站地址" name="url" :rules="[{ required: true, message: '请输入网站地址' }]">
          <a-input v-model:value="formState.url" placeholder="请输入网站地址" />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formState.description" placeholder="请输入网站描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup name="FavoriteSites">
import { ref, onMounted, nextTick, createVNode } from 'vue';
import { PlusOutlined, ExclamationCircleOutlined, EditOutlined, DeleteOutlined, PushpinOutlined } from '@ant-design/icons-vue';
import { message, Modal, Form } from 'ant-design-vue';
import { BookmarksApi } from '@/views/index/api/BookmarksApi';

const formRef = ref();
const formState = ref({
  name: '',
  url: '',
  icon: '',
  description: ''
});

const loading = ref(false);
const addLoading = ref(false);
const showEdit = ref(false);
const isEdit = ref(false);
const current = ref(null);

// 分页参数
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(20);
const dataSource = ref([]);

// 搜索条件
const where = ref({
  searchText: '',
  pageNo: 1,
  pageSize: 20,
  sortField: 'clickCount',
  sortOrder: 'asc'
});

const resetForm = () => {
  formState.value = {
    name: '',
    url: '',
    icon: '',
    description: ''
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const openSite = async (site) => {
  try {
    // 更新点击次数
    await BookmarksApi.updateClickCount({ bookmarkId: site.bookmarkId });
    // 打开网站
    window.open(site.url, '_blank');
    // 刷新列表
    getList();
  } catch (error) {
    console.error('更新点击次数失败', error);
    message.error('更新点击次数失败：' + (error.message || '未知错误'));
  }
};

// 新增编辑点击
const openAddEdit = async (record) => {
  console.log('编辑按钮被点击，传入的record数据：', record);
  
  // 重置表单
  resetForm();
  
  if (record) {
    try {
      // 编辑模式，获取详情数据
      const result = await BookmarksApi.getBookmarkDetail({ bookmarkId: record.bookmarkId });
      console.log('获取详情数据：', result);
      if (result) {
        const data = result;
        // 更新表单数据
        formState.value = {
          name: data.name || '',
          url: data.url || '',
          icon: data.icon || '',
          description: data.description || ''
        };
        console.log('设置后的表单数据：', formState.value);
        current.value = data;
        isEdit.value = true;
      }
    } catch (error) {
      console.error('获取详情失败', error);
      message.error('获取详情失败：' + (error.message || '未知错误'));
      return;
    }
  } else {
    // 新增模式
    isEdit.value = false;
    current.value = null;
  }
  
  // 显示弹窗
  showEdit.value = true;
};

// 删除
const remove = (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的收藏吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      try {
        const params = {
          bookmarkId: record.bookmarkId
        };
        await BookmarksApi.deleteBookmark(params);
        message.success('删除成功');
        getList();
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败：' + (error.message || '未知错误'));
      }
    }
  });
};

const getFaviconUrl = (url) => {
  try {
    const urlObj = new URL(url);
    // 使用Google的favicon服务
    return `https://favicon.cccyun.cc/${urlObj.hostname}`;
  } catch (error) {
    console.error('解析URL失败', error);
  }
};
const handleSubmit = async () => {
  console.log('提交表单，当前表单数据：', formState.value);
  addLoading.value = true;
  try {
    const submitData = {
      name: formState.value.name,
      url: formState.value.url.startsWith('http') ? formState.value.url : `http://${formState.value.url}`,
      icon: getFaviconUrl(formState.value.url),
      description: formState.value.description
    };
    console.log('处理后的提交数据：', submitData);

    if (isEdit.value) {
      console.log('提交编辑表单', { ...submitData, bookmarkId: current.value.bookmarkId });
      await BookmarksApi.updateBookmark({ ...submitData, bookmarkId: current.value.bookmarkId });
      message.success('更新成功');
    } else {
      console.log('提交新增表单', submitData);
      await BookmarksApi.addBookmark(submitData);
      message.success('添加成功');
    }
    showEdit.value = false;
    resetForm();
    getList();
  } catch (error) {
    console.error('提交表单失败', error);
    message.error(isEdit.value ? '更新失败：' + (error.message || '未知错误') : '添加失败：' + (error.message || '未知错误'));
  } finally {
    addLoading.value = false;
  }
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    console.log('搜索条件：', where.value);
    console.log('搜索文本：', where.value.searchText);
    const result = await BookmarksApi.getBookmarksPage({
      ...where.value,
      searchText: where.value.searchText || ''
    });
    console.log('获取到的结果：', result);
    if (result) {
      dataSource.value = result.rows || [];
      total.value = result.totalRows || 0;
      pageNo.value = result.pageNo || 1;
      pageSize.value = result.pageSize || 20;
    } else {
      dataSource.value = [];
      total.value = 0;
      message.error(result?.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败：', error);
    dataSource.value = [];
    total.value = 0;
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 页码改变
const handlePageChange = (page, pageSize) => {
  where.value.pageNo = page;
  where.value.pageSize = pageSize;
  getList();
};

// 每页条数改变
const handleSizeChange = (current, size) => {
  where.value.pageNo = 1;
  where.value.pageSize = size;
  getList();
};

// 点击搜索
const reload = () => {
  where.value.pageNo = 1;
  getList();
};

// 清除搜索条件
const clear = () => {
  where.value.searchText = '';
  where.value.pageNo = 1;
  where.value.pageSize = 20;
  getList();
};

// 搜索输入处理
const onSearchInput = (e) => {
  console.log('搜索输入：', e.target.value);
  where.value.searchText = e.target.value;
};

// 切换置顶状态
const togglePin = async (site) => {
  try {
    await BookmarksApi.pinned({
      bookmarkId: site.bookmarkId,
      pinned: site.pinned === 'Y' ? 'N' : 'Y'
    });
    message.success(site.pinned === 'Y' ? '取消置顶成功' : '置顶成功');
    getList();
  } catch (error) {
    console.error('更新置顶状态失败', error);
    message.error('更新置顶状态失败：' + (error.message || '未知错误'));
  }
};

// 在组件挂载时获取数据
onMounted(() => {
  getList();
});
</script>

<style scoped lang="less">
.card {
  width: 100%;
  height: 100%;
  background-color: white;
  box-shadow: 0 0 6px hsla(0, 0%, 80%, 0.5);
  border-radius: 4px;
  padding: 10px;
  
  @media (max-width: 768px) {
    padding: 8px;
  }
}

.card-header {
  width: 100%;
  min-height: 50px;
  border-bottom: 1px #999999 solid;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    padding-bottom: 12px;
  }
}

.card-header-title {
  font-size: 18px;
  font-weight: 500;
  
  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.card-header-toolbar {
  display: flex;
  align-items: center;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.toolbar-space {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
}

.search-input {
  width: 200px;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.reset-btn, .add-btn {
  @media (max-width: 768px) {
    width: 100%;
  }
}

.btn-text {
  @media (max-width: 768px) {
    display: inline;
  }
}

.sort-field-select {
  width: 120px;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.sort-order-select {
  width: 100px;
  
  @media (max-width: 768px) {
    width: 100%;
  }
}

.card-body {
  width: 100%;
  height: calc(100% - 50px);
  overflow-y: auto;
  padding: 10px;
  
  @media (max-width: 768px) {
    height: calc(100% - 120px);
    padding: 8px;
  }
}

.site-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  padding: 10px;
  
  @media (max-width: 1024px) {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 10px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 8px;
  }
}

.site-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
  
  @media (max-width: 768px) {
    &:hover {
      transform: none;
    }
  }

  &.site-card-pinned {
    background-color: #f0f7ff;
    border: 1px solid #91caff;
  }
}

.site-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
  margin-right: 8px;
  
  @media (max-width: 768px) {
    width: 20px;
    height: 20px;
    margin-right: 6px;
  }
}

.site-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.site-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.site-name {
  font-size: 14px;
  font-weight: 500;
  margin: 0;
  word-break: break-word;
  
  @media (max-width: 768px) {
    font-size: 13px;
  }
}

.site-url {
  color: #1890ff;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  
  @media (max-width: 768px) {
    font-size: 11px;
  }
}

.site-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 4px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

.site-stats {
  color: #999;
  font-size: 12px;
  
  @media (max-width: 768px) {
    font-size: 11px;
  }
}

.site-actions {
  display: flex;
  gap: 8px;
  
  @media (max-width: 768px) {
    gap: 12px;
  }
}

.site-actions .ant-btn {
  @media (max-width: 768px) {
    padding: 4px 8px;
    min-width: 32px;
  }
}

.site-actions .icon-font {
  font-size: 16px;
  cursor: pointer;
  &:hover {
    color: #1890ff;
  }
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}

.bookmark-modal {
  @media (max-width: 768px) {
    .ant-modal {
      margin: 16px;
      max-width: calc(100vw - 32px);
    }
  }
}
</style>